package com.face.zf.preheater;

import cn.smartjavaai.common.entity.R;
import cn.smartjavaai.face.model.facerec.FaceRecModel;
import com.face.zf.model.FaceModel;
import com.face.zf.util.Base64Utils;
import com.face.zf.util.PropertiesPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Properties;

@Component
public class FaceRecModelPreloader {

    private static final Logger log = LoggerFactory.getLogger(FaceRecModelPreloader.class);
    protected static Properties application = PropertiesPool.obtainProperties();
    @Value("${imagebase64One}")
    private String imageBase64;


    @PostConstruct
    public void preloadModel() throws IOException {
        try {
            byte[] dummyData1 = Base64Utils.decodeBase64(imageBase64);
            byte[] dummyData2 = Base64Utils.decodeBase64(imageBase64);
            FaceRecModel model = FaceModel.getFaceRecModel();
            long startTime = System.currentTimeMillis();
            R<Float> floatR = model.featureComparison(dummyData1, dummyData2);
            if (floatR.isSuccess()) {
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                String scaledResult = String.valueOf(floatR.getData() * 100);
                String detModelName = application.getProperty("face.detection.model.name");
                String redModelName = application.getProperty("face.recognition.model.name");
                if (detModelName.equals("YOLOV5_FACE_320")) {
                    log.info("当前使用的人脸检测模型:{},会对相似度40-80的进行数值补偿", detModelName);
                }else if (detModelName.equals("YOLOV5_FACE_420")) {
                    log.info("当前使用的人脸检测模型:{}", detModelName);
                }
                log.info("当前使用的人脸识别模型:{}", redModelName);
                log.info("==============预热使用了:{}ms,人脸识别模型预热成功==============", duration);
                log.info("模型预热预热结果:{}", scaledResult);
            }
        } catch (Exception e) {
            log.error("模型预热失败: {}", e.getMessage());
        }
    }
}
